﻿namespace QFlow.Windows.Forms
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Linq;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using QFlow.Data;

    /// <summary>
    /// Category List form
    /// </summary>
    public partial class CategoriesList : Utils.BaseForm
    {
        #region [Constructor]
        /// <summary>
        /// Initializes a new instance of the <see cref="CategoriesList"/> class.
        /// </summary>
        public CategoriesList(QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
        }
        #endregion

        #region [helper]
        /// <summary>
        /// Fills the TreeView with categories
        /// </summary>
        private void FillTree()
        {
            this.treeCategories.Nodes.Clear();

            var roots = Context.ProductCategories.Where(c => c.ParentCategoryID == null).ToList();

            ProductCategory noneCategory = new ProductCategory { CategoryID = 0, Name = QFlow.Windows.Properties.Resources.TrNone };
            roots.Insert(0, noneCategory);

            var node = this.treeCategories.Nodes.Add(noneCategory.Name);
            node.Tag = noneCategory;

            for (int i = 1; i < roots.Count; i++)
            {
                node = this.treeCategories.Nodes.Add(roots[i].Name);
                node.Tag = roots[i];
                this.FillSubCategories(node, roots[i]);
            }
        }

        /// <summary>
        /// Fills sub categories recursivly.
        /// </summary>
        /// <param name="parentNode">The parent node.</param>
        /// <param name="category">The parent category.</param>
        private void FillSubCategories(TreeNode parentNode, ProductCategory category)
        {
            //Product Categories is a list of the children
            foreach (var cat in category.ProductCategories)
            {
                var node = parentNode.Nodes.Add(cat.Name);
                node.Tag = cat;
                this.FillSubCategories(node, cat);
            }
        }

        /// <summary>
        /// Shows the new category items.
        /// </summary>
        private void ShowNewCategoryItems()
        {
            this.NewtoolStripTextBox.Text = string.Empty;
            this.NewtoolStripTextBox.Visible = true;
            this.SavetoolStripButton.Visible = true;
            this.CanceltoolStripButton.Visible = true;
        }

        /// <summary>
        /// Hides the new category items.
        /// </summary>
        private void HideNewCategoryItems()
        {
            this.NewtoolStripTextBox.Visible = false;
            this.SavetoolStripButton.Visible = false;
            this.CanceltoolStripButton.Visible = false;
        }

        #endregion

        #region [Events]
        /// <summary>
        /// Handles the Load event of the CategoriesList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void CategoriesList_Load(object sender, EventArgs e)
        {
            this.FillTree();
        }

        /// <summary>
        /// Handles the AfterSelect event of the treeCategories control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param>
        private void TreeCategories_AfterSelect(object sender, TreeViewEventArgs e)
        {
            ProductCategory category = e.Node.Tag as ProductCategory;
            gvProducts.AutoGenerateColumns = false;
            if (category.CategoryID != 0)
                this.gvProducts.DataSource = category.Products.ToArray();
            else this.gvProducts.DataSource = null;
        }

        /// <summary>
        /// Handles the Click event of the DeletetoolStripButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DeletetoolStripButton_Click(object sender, EventArgs e)
        {
            if (this.treeCategories.SelectedNode != null)
            {
                if (this.treeCategories.SelectedNode.Parent != null || this.treeCategories.SelectedNode.Index != 0)
                {
                    if (MessageBox.Show(QFlow.Windows.Properties.Resources.MBDeleteCategory, QFlow.Windows.Properties.Resources.MBQuestionCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        try
                        {
                            var category = this.treeCategories.SelectedNode.Tag as ProductCategory;
                            if (category.ProductCategory1 != null)
                            {
                                category.ProductCategory1 = null;
                                this.Context.ProductCategories.DeleteOnSubmit(category);
                            }
                            else
                            {
                                this.Context.ProductCategories.DeleteOnSubmit(category);
                            }
                            this.Context.SubmitChanges();

                            this.FillTree();
                        }
                        catch
                        {
                            MessageBox.Show(QFlow.Windows.Properties.Resources.MBCantDeleteCategory, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                            ResetContext();
                        }
                    }
                }
            }
        }
        #endregion

        #region [create new category]
        /// <summary>
        /// Handles the Click event of the NewStripButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void NewStripButton_Click(object sender, EventArgs e)
        {
            this.ShowNewCategoryItems();
        }

        /// <summary>
        /// Handles the Click event of the SavetoolStripButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SavetoolStripButton_Click(object sender, EventArgs e)
        {
            string categoryName = null;

            //----------------------------------------------------
            if (string.IsNullOrEmpty(this.NewtoolStripTextBox.Text))
            {
                MessageBox.Show(QFlow.Windows.Properties.Resources.GVEmptyValue);
                return;
            }

            categoryName = this.NewtoolStripTextBox.Text;

            var category = new ProductCategory { Name = categoryName };

            try
            {
                if (this.treeCategories.SelectedNode.Parent != null || this.treeCategories.SelectedNode.Index != 0)
                {
                    var parentCategory = this.treeCategories.SelectedNode.Tag as ProductCategory;
                    parentCategory.ProductCategories.Add(category);
                }
                else
                {
                    this.Context.ProductCategories.InsertOnSubmit(category);
                }
                this.Context.SubmitChanges();

                this.FillTree();
                this.HideNewCategoryItems();
            }
            catch
            {
                MessageBox.Show(QFlow.Windows.Properties.Resources.MBCantSaveChanges, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        /// <summary>
        /// Handles the Click event of the CanceltoolStripButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void CanceltoolStripButton_Click(object sender, EventArgs e)
        {
            this.HideNewCategoryItems();
        }
        #endregion

        #region [Update]

        /// <summary>
        /// Handles the BeforeLabelEdit event of the treeCategories control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.NodeLabelEditEventArgs"/> instance containing the event data.</param>
        private void treeCategories_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (this.treeCategories.SelectedNode.Parent == null && this.treeCategories.SelectedNode.Index == 0)
                e.CancelEdit = true;
        }

        /// <summary>
        /// Handles the AfterLabelEdit event of the treeCategories control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.NodeLabelEditEventArgs"/> instance containing the event data.</param>
        private void treeCategories_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.CancelEdit || string.IsNullOrEmpty(e.Label))
                return;

            var category = e.Node.Tag as ProductCategory;
            category.Name = e.Label;

            this.Context.SubmitChanges();
        }
        #endregion
    }
}
